// WebSocket 管理类
class WebSocketManager {
    constructor() {
        this.socket = null;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.initialize();
    }

    // 初始化WebSocket连接
    initialize() {
        this.socket = io({
            transports: ['websocket'],
            upgrade: false
        });

        this.setupEventListeners();
    }

    // 设置事件监听器
    setupEventListeners() {
        this.socket.on('connect', () => {
            this.updateStatus(true);
            this.logDebug('WebSocket 连接成功');
            this.reconnectAttempts = 0;
        });

        this.socket.on('disconnect', () => {
            this.updateStatus(false);
            this.logDebug('WebSocket 连接断开');
            this.attemptReconnect();
        });

        this.socket.on('scan_result', (data) => {
            this.logDebug(`收到扫描结果: ${JSON.stringify(data)}`);
            if (data.success) {
                window.soundManager.playSound('scanSound');
                window.notificationManager.showMessage(`包裹 ${data.package_id} 扫描成功`, 'success');
            } else {
                window.soundManager.playSound('errorSound');
                window.notificationManager.showMessage(data.error || '扫描失败', 'error');
            }
        });

        this.socket.on('batch_stats_update', (data) => {
            this.logDebug(`收到批次统计更新: ${JSON.stringify(data)}`);
            if (window.packageTracker) {
                window.packageTracker.updateBatchStats(data);
            }
        });
    }

    // 更新WebSocket状态显示
    updateStatus(connected) {
        const indicator = document.getElementById('ws-indicator');
        const text = document.getElementById('ws-text');
        
        if (connected) {
            indicator.className = 'h-3 w-3 rounded-full bg-green-500';
            text.textContent = 'WebSocket 已连接';
            text.className = 'text-sm font-medium text-green-600';
        } else {
            indicator.className = 'h-3 w-3 rounded-full bg-red-500';
            text.textContent = 'WebSocket 已断开';
            text.className = 'text-sm font-medium text-red-600';
        }
    }

    // 记录调试信息
    logDebug(message) {
        const debugLog = document.getElementById('debug-log');
        const time = new Date().toLocaleTimeString();
        const logEntry = document.createElement('div');
        logEntry.className = 'text-xs text-gray-600';
        logEntry.textContent = `[${time}] ${message}`;
        debugLog.insertBefore(logEntry, debugLog.firstChild);
        
        // 保持最多显示 50 条日志
        while (debugLog.children.length > 50) {
            debugLog.removeChild(debugLog.lastChild);
        }
    }

    // 重连机制
    attemptReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            setTimeout(() => {
                this.socket.connect();
            }, 1000 * Math.pow(2, this.reconnectAttempts));
        } else {
            window.notificationManager.showMessage('WebSocket 连接失败，请刷新页面重试', 'error');
        }
    }

    // 加入批次
    joinBatch(batchId) {
        if (this.socket) {
            this.socket.emit('join', { batch_id: batchId });
        }
    }

    // 离开批次
    leaveBatch(batchId) {
        if (this.socket) {
            this.socket.emit('leave', { batch_id: batchId });
        }
    }

    // 发送扫描请求
    sendScanRequest(packageId, batchId) {
        if (this.socket) {
            this.logDebug(`发送扫描请求: ${packageId}, 批次: ${batchId}`);
            this.socket.emit('scan_package', {
                package_id: packageId,
                batch_id: batchId
            });
        }
    }
}

// 创建全局WebSocket管理器实例
window.wsManager = new WebSocketManager();

// 添加调试面板快捷键
document.addEventListener('keydown', function(e) {
    if (e.ctrlKey && e.shiftKey && e.key === 'D') {
        const debugPanel = document.getElementById('debug-panel');
        debugPanel.style.display = debugPanel.style.display === 'none' ? 'block' : 'none';
    }
}); 